﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Entities;
namespace Data
{
  public class NguoiDungRepository
    {
      public static NguoiDungDTO GetNguoiDungByTenDangNhap(string tenDangNhap)
      {
          NhaSachEntities context = new NhaSachEntities();
          var q = (from nd in context.NguoiDungList
                   where nd.TenDangNhap == tenDangNhap
                   select new NguoiDungDTO()
                   {
                       TenDangNhap = nd.TenDangNhap,
                       HoTen = nd.HoTen,
                       MatKhau = nd.MatKhau,
                       MaChucVu = (int)nd.MaChucVu,
                       TinhTrang = (int)nd.TinhTrang
                   }).FirstOrDefault();
          return q;
      }
      public static List<NguoiDungDTO> GetNguoiDungList()
      {
          NhaSachEntities context = new NhaSachEntities();
          var q = (from nd in context.NguoiDungList                   
                   select new NguoiDungDTO()
                   {
                       TenDangNhap = nd.TenDangNhap,
                       HoTen = nd.HoTen,
                       MatKhau = nd.MatKhau,
                       MaChucVu = (int)nd.MaChucVu,
                       TinhTrang = (int)nd.TinhTrang
                   }).DefaultIfEmpty();
          return q.ToList();
      }
      public static void Update(NguoiDungDTO nguoiDung)
      {
          NhaSachEntities context = new NhaSachEntities();
          var q = (from nd in context.NguoiDungList
                   where nguoiDung.TenDangNhap == nd.TenDangNhap
                   select nd).FirstOrDefault();
          q.TenDangNhap = nguoiDung.TenDangNhap;
          q.HoTen = nguoiDung.HoTen;
          q.MatKhau = nguoiDung.MatKhau;
          q.MaChucVu = nguoiDung.MaChucVu;
          q.TinhTrang = nguoiDung.TinhTrang;
          context.SaveChanges();
      }
      public static void Insert(NguoiDungDTO nguoiDung)
      {
          NhaSachEntities context = new NhaSachEntities();
          NguoiDung nd = new NguoiDung();

          nd.TenDangNhap = nguoiDung.TenDangNhap;
          nd.HoTen = nguoiDung.HoTen;
          nd.MatKhau = nguoiDung.MatKhau;
          nd.MaChucVu = nguoiDung.MaChucVu;
          nd.TinhTrang = nguoiDung.TinhTrang;

          context.AddToNguoiDungList(nd);
          context.SaveChanges();
      }

      public static void Delete(string tenDangNhap)
      {
          NhaSachEntities context = new NhaSachEntities();

          var q=(from nd in context.NguoiDungList
                 where nd.TenDangNhap==tenDangNhap
                 select nd).FirstOrDefault();

          context.NguoiDungList.DeleteObject(q);
          context.SaveChanges();
      }
    }
}
